package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;
    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItem.setCreateTime(new Date());
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        /**
         * 1.如果是上架状态，不允许修改的,抛出异常
         *       2.如果是下架状态
         *               非套餐(不需要处理)
         *               套餐，如果是审核中,不能进行编辑，抛出异常
         *         如果是下架状态，套餐，处于审核通过,如果此时修改，应该把状态修改成初始化
         *         其他情况，原来是什么状态，应该设置什么状态.
         *                非套餐--->无需审核
         *                套餐   ---->初始化，重新发起
         *         防止前台恶意对销售状态进行设置，代码中主动设置销售状态为下架状态
         */
        ServiceItem oldObj = this.get(serviceItem.getId());
        System.out.println("=================" + oldObj);
        if (ServiceItem.SALESTATUS_ON.equals(oldObj.getSaleStatus())) {
            throw new BusinessException("服务单项处于上架状态,不允许修改");
        }
        if (ServiceItem.CARPACKAGE_YES.equals(oldObj.getCarPackage()) && ServiceItem.AUDITSTATUS_AUDITING.equals(oldObj.getAuditStatus())) {
            throw new BusinessException("服务单项处于审核状态,不允许修改");
        }
        if (ServiceItem.CARPACKAGE_YES.equals(oldObj.getCarPackage()) && ServiceItem.AUDITSTATUS_APPROVED.equals(oldObj.getAuditStatus())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            serviceItem.setAuditStatus(oldObj.getAuditStatus());
        }
        if(ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }
        if (ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    public void saleOn(Long id) {
        ServiceItem serviceItem = this.get(id);
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage()) && !ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())) {
            throw new BusinessException("套餐服务审核未通过,不能上架");
        }
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_ON);
    }

    @Override
    public void saleOff(Long id) {
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_OFF);
    }

    @Override
    @Transactional
    public void startAudit(Long id, Long bpmnInfoId, Long directorId, Long financialId, String info) {
        //根据传入的id查询服务项，服务项状态出于初始化才能进行审核逻辑
        ServiceItem serviceItem =  this.get(id);
        System.out.println("=====================" +serviceItem);
        if(serviceItem==null || ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())
            || ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus())
            || ServiceItem.AUDITSTATUS_NO_REQUIRED.equals(serviceItem.getAuditStatus())){
            throw new BusinessException("参数异常");
        }
        //修改服务状态，修改为审核中
        serviceItemMapper.changeAuditStatus(id, ServiceItem.AUDITSTATUS_AUDITING);
        CarPackageAudit audit = new CarPackageAudit();
        audit.setServiceItemId(id);
        audit.setServiceItemInfo(serviceItem.getInfo());
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());
        audit.setCreateTime(new Date());
        audit.setCreator(ShiroUtils.getUser().getUserName());
        audit.setBpmnInfoId(bpmnInfoId);
        audit.setInfo(info);
        audit.setAuditorId(directorId);
        audit.setServiceItemName(serviceItem.getName());
        carPackageAuditService.save(audit);
        Map<String, Object> map = new HashMap<>();
        if(directorId != null){
            map.put("director", directorId.toString());
        }
        if(financialId != null){
            map.put("finance", financialId.toString());
        }
        map.put("discountPrice", serviceItem.getDiscountPrice().longValue());
        // 根据BpmnId获取流程定义key启动流程实例
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(bpmnInfo.getActProcessKey(), audit.getId().toString(), map);
        //更新记录实例id
        audit.setInstanceId(processInstance.getId());
        carPackageAuditService.updateInstanceId(audit.getInstanceId(),audit.getId());
    }

    @Override
    public void changeAuditStatus(Long id, Integer status) {
        serviceItemMapper.changeAuditStatus(id,status);
    }


}
